package com.sen.gateway.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.sen.common.auth.properties.SecurityProperties;
import com.sen.common.common.bo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.AntPathMatcher;

import java.util.List;

/**
 * 请求权限判断service
 *
 * @author esjiang
 */
@Slf4j
public abstract class DefaultPermissionServiceImpl {

    @Autowired
    private SecurityProperties securityProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(Authentication authentication, ServerHttpRequest request) {
        /** 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现 */
        String requestURI = request.getURI().getPath();
        String requestMethod = request.getMethodValue();
        /** 超管直接放行 */
        String username = ((User) authentication.getPrincipal()).getUsername();
        if (StrUtil.equals(username,securityProperties.getAdmin())){
            return true ;
        }
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) {
            return true;
        }
        for (String path : securityProperties.getAllPermitUrls()){
            if (antPathMatcher.match(path, requestURI)) {
                return true;
            }
        }
        if (!(authentication instanceof AnonymousAuthenticationToken)) {

            /** 判断不进行url权限认证的api，所有已登录用户都能访问的url */
            for (String path : securityProperties.getIgnoreUrls()) {
                if (antPathMatcher.match(path, requestURI)) {
                    return true;
                }
            }

            List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
            if (CollectionUtil.isEmpty(grantedAuthorityList)) {
                log.warn("权限列表为空：{}", authentication.getPrincipal());
                return false;
            }

            for (SimpleGrantedAuthority authority : grantedAuthorityList) {
                if (StringUtils.isNotEmpty(authority.getAuthority()) && antPathMatcher.match(authority.getAuthority(), requestURI)) {
                   return true;
               }
            }
        }
        return false;
    }

}
